package obj;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Table {
	public String tableName = "";
	public ArrayList<Version> versions = new ArrayList<Version>();

	public Table(String filename, String fileContent) {
		try {
			JSONObject table = new JSONObject(fileContent);
			tableName = table.getString("table_name");

			JSONArray listVersions = table.getJSONArray("versions");
			for (int i = 0; i < listVersions.length(); i++) {
				createVersion(listVersions.getJSONObject(i));
			}

		} catch (JSONException e) {
			System.out.println("Error processing File : <" + filename + ">");
			System.exit(-1);
		}
	}

	private void createVersion(JSONObject versionObj) {

		try {
			int vname = versionObj.getInt("vname");

			ArrayList<String> references = new ArrayList<String>();
			ArrayList<String> sql = new ArrayList<String>();

			if (versionObj.has("references")) {
				JSONArray temp_references = versionObj
						.getJSONArray("references");
				for (int i = 0; i < temp_references.length(); i++) {
					references.add(temp_references.getString(i));
				}
			}

			JSONArray list_sql = versionObj.getJSONArray("sql");

			for (int i = 0; i < list_sql.length(); i++) {
				sql.add(list_sql.getString(i));
			}
			versions.add(new Version(vname, references, sql));

		} catch (JSONException e) {

			e.printStackTrace();
		}

	}

	public Version getNextVersion(int currentVersion) {
		Version result = null;
		for (int i = 0; i < versions.size(); i++) {
			Version temp = versions.get(i);
			if (temp.version > currentVersion) {
				if (result == null) {
					result = temp;
				} else if (temp.version < result.version) {
					result = temp;
				}
			}
		}
		return result;
	}
}
